package com.example.unisys.service;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.unisys.common.QueryRequest;
import com.example.unisys.dao.RoleMapper;
import com.example.unisys.entity.Role;
import com.example.unisys.entity.RoleMenu;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class RoleService extends ServiceImpl<RoleMapper, Role> {

    //    @Autowired
//    private RoleMenuMapper roleMenuMapper;
//    @Autowired
//    private UserRoleService userRoleService;
    @Autowired
    private RoleMenuService roleMenuService;
//    @Autowired
//    private UserManager userManager;

    public IPage<Role> findRoles(Role role, QueryRequest request) {
        try {
            LambdaQueryWrapper<Role> queryWrapper = new LambdaQueryWrapper<>();

            if (StringUtils.isNotBlank(role.getRole_name())) {
                queryWrapper.eq(Role::getRole_name, role.getRole_name());
            }
//            if (StringUtils.isNotBlank(role.getCreatetime()) && StringUtils.isNotBlank(role.getCreateTimeTo())) {
//                queryWrapper
//                        .ge(Role::getCreateTime, role.getCreateTimeFrom())
//                        .le(Role::getCreateTime, role.getCreateTimeTo());
//            }
            Page<Role> page = new Page<>();

            return this.page(page, queryWrapper);
        } catch (Exception e) {
            log.error("获取角色信息失败", e);
            return null;
        }
    }


    public List<Role> findUserRole(int user_type) {
        return baseMapper.findUserRoles(user_type);
    }

//    public Role findByName(String roleName) {
//        return baseMapper.selectOne(new LambdaQueryWrapper<Role>().eq(Role::getRoleName, roleName));
//    }

    public void createRole(Role role) {
        role.setCreate_time(new Date());
        this.save(role);

//        String[] menuIds = role.getRole_id().split(StringPool.COMMA);
        String[] menuIds = {""};
        setRoleMenus(role, menuIds);
    }

//    public void deleteRoles(String[] roleIds) throws Exception {
//        // 查找这些角色关联了那些用户
//        List<String> userIds = this.userRoleService.findUserIdsByRoleId(roleIds);
//
//        List<String> list = Arrays.asList(roleIds);
//
//        baseMapper.deleteBatchIds(list);
//
//        this.roleMenuService.deleteRoleMenusByRoleId(roleIds);
//        this.userRoleService.deleteUserRolesByRoleId(roleIds);
//
//        // 重新将这些用户的角色和权限缓存到 Redis中
//        this.userManager.loadUserPermissionRoleRedisCache(userIds);
//
//    }

//    public void updateRole(Role role) throws Exception {
//        // 查找这些角色关联了那些用户
//        String[] roleId = {String.valueOf(role.getRole_id())};
//        List<String> userIds = this..findUserIdsByRoleId(roleId);
//
//        role.setModifyTime(new Date());
//        baseMapper.updateById(role);
//
//        roleMenuMapper.delete(new LambdaQueryWrapper<RoleMenu>().eq(RoleMenu::getRoleId, role.getRoleId()));
//
//        String[] menuIds = role.getMenuId().split(StringPool.COMMA);
//        setRoleMenus(role, menuIds);
//
//        // 重新将这些用户的角色和权限缓存到 Redis中
//        this.userManager.loadUserPermissionRoleRedisCache(userIds);
//    }

    private void setRoleMenus(Role role, String[] menuIds) {
        Arrays.stream(menuIds).forEach(menuId -> {
            RoleMenu rm = new RoleMenu();
            rm.setMenu_id(Long.valueOf(menuId));
            rm.setRole_id(role.getRole_id());
            this.roleMenuService.insert(rm);
        });
    }
}
